/**
* @file qotcp.cpp
* @describe QoTcp模块
* @author gaoyuelong
* @date 2022/05/02
*/

#include "qotcp.h"
#include "common.h"
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>

#define WAITFORCONNECTEDTIME 5000
#define WAITFORREADYREAD 10000

QoTcp *QoTcp::getInstance()
{
    static QoTcp qoTcp;
    return &qoTcp;
}

bool QoTcp::isConnected()
{
    return m_pTcpSocket->waitForConnected(WAITFORCONNECTEDTIME);
}

void QoTcp::connectToServer()
{
    if (m_pTcpSocket) {
        m_pTcpSocket->connectToHost("42.192.22.128", 8888);
    }
}

void QoTcp::sendMsg(const QString &strMsg)
{
    if (!isConnected()) {
        if (!reconnect()) {
            return;
        }
    }

    qDebug() << "sendMsg" << strMsg;
    QByteArray byteArray;
    byteArray.append(strMsg);
    const char *pCharMsg = byteArray.data();
    qDebug() << "length: " << m_pTcpSocket->write(pCharMsg, byteArray.size() + 1);
}

bool QoTcp::recvMsg(QJsonObject &jsonObj)
{
    //if (m_pTcpSocket->waitForReadyRead(WAITFORREADYREAD)) {

    QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
    jsonObj = jsonDoc.object();
    if (!jsonObj.isEmpty()) return true;
    return false;
}

void QoTcp::slotRecvMsg()
{
    //数据可读时，先备份一份，qomodel和qousermodel都会读数据
    byteArray = m_pTcpSocket->readAll();
    qDebug() << "RECV: " << byteArray;
}

bool QoTcp::reconnect()
{
    connectToServer();
    return isConnected();
}

QoTcp::QoTcp()
{
    m_pTcpSocket = new QTcpSocket();

    connect(m_pTcpSocket, SIGNAL(readyRead()), this, SLOT(slotRecvMsg()));
    connect(m_pTcpSocket, SIGNAL(readyRead()), this, SIGNAL(signalRecvMsg()));
}

QoTcp::~QoTcp()
{
    m_pTcpSocket->close();
}
